/*****************************************************************
**                                                              **
**  Copyright (C) 2004 Amlogic,Inc.                             **
**  All rights reserved                                         **
**        Filename : aw_user.c /Project:AVOS                    ** 
**        Revision : 1.0                                        **
**                                                              **
*****************************************************************/
#ifdef ENABLE_NETWORK_BASIC
#include "../menu.h"
#include "includes.h"
#include "aw_windows.h"
#include "app.h"
#include "user.h"
#include "menu.h"
#include "aw_init_display.h"
#include "logo_dat.h" 
#include "LogoEvent.h"
#include "aw_sys_app.h"
#include "aw_gui_app.h"

#include "filenav.h"

#include "net_app.h"
#include "netdiskdev.h"
#ifdef BROWSER_SUPPORT
#include "DeviceSelectEvent.h"
#endif

#define MENU_NETWORK 6
#include "aw_network.h"
#include "NetmenuSetupEvent.h"
INT32U network_status=0;
#endif/*ENABLE_NETWORK_BASIC*/

#ifdef ENABLE_NETWORK
#include"Network_SetupEvent.h"
#include "winwarnMessageBoxEvent.h"
extern int SHOW_WINDOW_NUM;
extern struct iwscan_state *Scan_Result; /*scan result struct pointer*/
extern INT8U	menu_index_process;  /*current menu index*/
extern u8_t    net_cont_status;            /*a flag show if current is connecting to a AP,if the flag=CONNECTING show the connecting operation is go-on.*/
extern u8_t    net_entrance;                 /*a flag show the UI has enter network menu,if enter the flag>0,else flag=0*/
int           usbnet_device_plug = 0;      /* a usb net device plugin flag,when plugin,the flag>0,else flag=0*/
INT8U      network_connected_flag=0; /*connected to network flag,when connected the flag>0,else flag=0*/
//extern void InitPreviewList(void);

typedef void (*NetFsBrowserTask_t)(void *opt);
#define  NETFS_BROWSER_STACK_SIZE                 (4*1024)       
static OS_STK taskstk_netfs_browser[NETFS_BROWSER_STACK_SIZE];
unsigned short NetFsBrowserTaskStart(NetFsBrowserTask_t NetFsBrowserTask)
{
    unsigned short taskid=0;
    AVTaskCreate(NetFsBrowserTask, 0, &taskstk_netfs_browser[NETFS_BROWSER_STACK_SIZE - 1], 20, &taskid);
    return taskid;
}

void AWNetNotificationProcess(AWMSG *pMsg)
{
	switch(pMsg->msg_id)
	{
		case NM_NET_WIFI_SCANPROGRESS:
		{
			Scan_Result = (struct iwscan_state *) pMsg->msg_value;
			UI_Display_Scanresult(Scan_Result);            
			break;
		}
        
		case NM_NET_WIFI_CONNPROGRESS:
		{
			struct iwconfig_state *config = (struct iwconfig_state *) pMsg->msg_value;
			
			if ((config->progress >= config->timeout)&&(!config->errno))		 
			{
				/*Get IP address*/
				struct netif_config net_config;

				if (netif_get_config(&net_config))
				{
					//AVOS_printf("get config error\n");
					return;
				}
				else{
					if (net_config.ipaddr.s_addr)
					{                        	
						inet_ntoa_r(net_config.ipaddr, ip_config_info[0]);
						//UpdateAddrArrange(ip_str);
					}
				   	
					 if (net_config.netmask.s_addr)
					{                        	
						inet_ntoa_r(net_config.netmask, ip_config_info[1]);
						//UpdateAddrArrange(mask_str);
					}	
					
					if (net_config.gateway.s_addr)
					{                        	
						inet_ntoa_r(net_config.gateway, ip_config_info[2]);
						//UpdateAddrArrange(gateway_str);
					}
					if (net_config.primary_dns.s_addr)
					{                        	
						inet_ntoa_r(net_config.primary_dns, ip_config_info[3]);
						//UpdateAddrArrange(pdns_str);
					}	
					if (net_config.secondary_dns.s_addr)
					{                        	
						inet_ntoa_r(net_config.secondary_dns, ip_config_info[4]);
						//UpdateAddrArrange(sdns_str);
					}	
					if(net_config.hwaddr)
					{
						/*Get Mac Address here*/           
						/* Display MAC address. */
						sprintf(ip_config_info[5],
							"MAC :                        %02X:%02X:%02X:%02X:%02X:%02X",
							net_config.hwaddr[0],
							net_config.hwaddr[1],
							net_config.hwaddr[2],
							net_config.hwaddr[3],
							net_config.hwaddr[4],
							net_config.hwaddr[5]);
                   
         
						//memcpy(mac_addr,net_config.hwaddr,6);
					}
                        		
					//sprintf(ip_config_info[0],"%s",net_config.ipaddr.s_addr);
					
					menu_index_process=ID_MENU_GETIPADDRESS_SUCCESS1;
					net_cont_status = NONE;
					//strcpy(ip_config_info[0],net_config.ipaddr.s_addr);	
						/*
						netif_config.ipaddr   IP address
						netif_config.netmask   mask
						netif_config.igateway   gateway
						netif_config.primary_dns   DNS    
						*/
						
				
				}
//				change_message(menu_index_process);
				if(AWGetTopWindow(gpFocusWin) == AWFindWinCtrlByName("WinWarnMessageBox"))
				{
					repaint_message();
				}
                /*		
                else 
		       	{
					GUIShowWindow("WinWarnMessageBox");
				}
                */   			
			}

			if(config->errno)
			{
				net_cont_status = NONE;
				switch(config->errno)
				{
					case -ENODEV:
					{
						/*No network device is detected*/
						//faild_condition_flag=0;
						menu_index_process=ID_NET_FAILED_MESSAGE_STR1;                    		
						break;
					}                    	
					case -EOPNOTSUPP:
					{
						/*Operation is not supported on the network device*/
						//faild_condition_flag=1;
						menu_index_process=ID_NET_FAILED_MESSAGE_STR2;
						break;
					}
                    	
					case -E2BIG:
					case -EFAULT:
					{
						/*Parameters sent to the device driver is not correct*/
						//faild_condition_flag=2;
						menu_index_process=ID_NET_FAILED_MESSAGE_STR3;
						break;
					}
					case -EINVAL:
					{
						/*Invalid operation is requested*/
						//faild_condition_flag=3;
						menu_index_process=ID_NET_FAILED_MESSAGE_STR4;
						break;
					}
                    	
					case -ENOSR:
					case -ENOMEM:
					{
						/*System is running out some resource*/
						//faild_condition_flag=4;
						menu_index_process=ID_NET_FAILED_MESSAGE_STR5;
						break;
					}
                    	
					case -ETIME:
					{
						/*Attempt to connect to AP timed out*/
						//faild_condition_flag=5;
						menu_index_process=ID_NET_FAILED_MESSAGE_STR6;
						break;
					}
                    	
					case -ENOIPADDR:
					{
						/*No IP address is available for the network device*/
						//faild_condition_flag=6;
						menu_index_process=ID_NET_FAILED_MESSAGE_STR7;
						break;
					}
    
                    	
					case 0xff:	/*this is special for Auth successful*/	         
					{
						net_cont_status = CONNECTING;
						 
						if( menu_index_process==ID_NET_AUTH_SUCCESS_STR)
						{
							return;
						}        
						menu_index_process=ID_NET_AUTH_SUCCESS_STR;   
	           
						break;
					}
					default:
					{
						// faild_condition_flag=7;     
						menu_index_process=ID_NET_FAILED_MESSAGE_STR8;                   
						break;
					}
			}
                    
                
			// PresetMenuProcess_Info(ID_MENU_INFO_FAILED);
			 //  RestartPaintInfo();
			//printf("Connect failed: errno %d\n", config->errno);
//			change_message(menu_index_process);
			if(AWGetTopWindow(gpFocusWin) == AWFindWinCtrlByName("WinWarnMessageBox"))
			{
				 repaint_message();
			}
		
		}
            break;
        
		}

		case NM_NET_SNTP_SYNC:
		{
#if 0
            time_t t;
            struct tm *lt;

            //Display Pacific local time.
            //avos_tzset("+8:00", 1);

            t  = pMsg->msg_value;
            lt = localtime(&t);

#if 0
            printf("Local time %s", asctime(lt));
            printf("TIMEZONE %d\n", _timezone);
            printf("DAYLIGHT %d\n", _daylight);
#endif
            AVSchedLock();
            lt->tm_year=lt->tm_year+1900;
            lt->tm_mon=lt->tm_mon+1;
            WrRTCClk(*lt);
            AVSchedUnlock();  
#endif
            break;
		}
		case NM_NET_SERVICE_RESPONSE:
		{
#if 0
            net_service_command_t *cmd = (net_service_command_t *)pMsg->msg_value;

            if (strcmp(cmd->name, NET_SERVICE_YAHOO) == 0) {
                if (cmd->message == NM_YAHOO_WEATHER_GET) {
                    yahoo_weather_request_t *request = cmd->data;

                    if (cmd->status == YAHOO_ERR_none) {
                        yahoo_weather_dump2vosd(yahoo_vosd, request->report);
                        yahoo_weather_delete(request->report);
                    }

                    AVMem_free(request->location);
                    AVMem_free(request);
                }
                else if (cmd->message == NM_YAHOO_TRAFFIC_GET) {
                    yahoo_traffic_request_t *request = cmd->data;

                    if (cmd->status == YAHOO_ERR_none) {
                        yahoo_traffic_dump2vosd(yahoo_vosd, request->info);
                        yahoo_traffic_delete(request->info);
                    }

                    AVMem_free(request->zip);
                    AVMem_free(request);
                }
                else if (cmd->message == NM_YAHOO_STOCK_GET) {
                    yahoo_stock_request_t *request = cmd->data;

                    if (cmd->status == YAHOO_ERR_none) {
                        yahoo_stock_dump2vosd(yahoo_vosd, request->quote);
                        yahoo_stock_delete(request->quote);
                    }

                    AVMem_free(request->symbol);
                    AVMem_free(request);
                }
                else if (cmd->message == NM_YAHOO_WEATHER_SUBSCRIBE) {
                    yahoo_weather_request_t *request = cmd->data;

                    if (cmd->status == YAHOO_ERR_none) {
                        yahoo_weather_dump2vosd(yahoo_vosd, request->report);
                        yahoo_weather_delete(request->report);

                        /* Save subscription handle. */
                        yahoo_weather_subscription = cmd->subscription.handle;
                    }

                    AVMem_free(request->location);
                    AVMem_free(request);
                }
                else if (cmd->message == NM_YAHOO_WEATHER_UNSUBSCRIBE) {
                    yahoo_weather_subscription = NULL;
                }
                else if (cmd->message == NM_YAHOO_STOCK_SUBSCRIBE) {
                    yahoo_stock_request_t *request = cmd->data;

                    if (cmd->status == YAHOO_ERR_none) {
                        yahoo_stock_dump2vosd(yahoo_vosd, request->quote);
                        yahoo_stock_delete(request->quote);

                        /* Save subscription handle. */
                        yahoo_stock_subscription = cmd->subscription.handle;
                    }

                    AVMem_free(request->symbol);
                    AVMem_free(request);
                }
                else if (cmd->message == NM_YAHOO_STOCK_UNSUBSCRIBE) {
                    yahoo_stock_subscription = NULL;
                }
                else if (cmd->message == NM_YAHOO_TRAFFIC_SUBSCRIBE) {
                    yahoo_traffic_request_t *request = cmd->data;

                    if (cmd->status == YAHOO_ERR_none) {
                        yahoo_traffic_dump2vosd(yahoo_vosd, request->info);
                        yahoo_traffic_delete(request->info);

                        /* Save subscription handle. */
                        yahoo_traffic_subscription = cmd->subscription.handle;
                    }

                    AVMem_free(request->zip);
                    AVMem_free(request);
                }
                else if (cmd->message == NM_YAHOO_TRAFFIC_UNSUBSCRIBE) {
                    yahoo_traffic_subscription = NULL;
                }
            }

            AVMem_free(cmd);
#endif
			break;
		}
		case NM_NET_SERVICE_UPDATE:
		{
#if 0
            net_service_command_t *cmd = (net_service_command_t *)pMsg->msg_value;

            if (strcmp(cmd->name, NET_SERVICE_YAHOO) == 0) {
                if (cmd->message == NM_YAHOO_WEATHER_UPDATE) {
                    yahoo_weather_t *report = cmd->data;

                    if (cmd->status == YAHOO_ERR_none) {
                        yahoo_weather_dump2vosd(yahoo_vosd, report);
                        yahoo_weather_delete(report);
                    }

                    /* Cancel subscription. */
                    yahoo_service_weather_unsubscribe(yahoo_weather_subscription);
                }
                else if (cmd->message == NM_YAHOO_STOCK_UPDATE) {
                    yahoo_stock_t *quote = cmd->data;

                    if (cmd->status == YAHOO_ERR_none) {
                        yahoo_stock_dump2vosd(yahoo_vosd, quote);
                        yahoo_stock_delete(quote);
                    }

                    /* Cancel subscription. */
                    yahoo_service_stock_unsubscribe(yahoo_stock_subscription);
                }
                else if (cmd->message == NM_YAHOO_TRAFFIC_UPDATE) {
                    yahoo_traffic_t *info = cmd->data;

                    if (cmd->status == YAHOO_ERR_none) {
                        yahoo_traffic_dump2vosd(yahoo_vosd, info);
                        yahoo_traffic_delete(info);
                    }

                    /* Cancel subscription. */
                    yahoo_service_traffic_unsubscribe(yahoo_traffic_subscription);
                }
            }

            AVMem_free(cmd);
#endif
			break;
		}
	}
}


void AWNetBroadCastProcess(AWMSG *pMsg)
{
	switch(pMsg->msg_id)
	{
	case BM_DIR_REFRESH:
    /**
     * format:
     * {count of items (1 byte);  path_type_item ; {name_type_item ; other_type_item ; ... other_type_item}; { name_type_item; other_type_item; ... other_type_item} ... }
     * item :  {type(1 byte); size (1 byte) ; data (size bytes)}
     * type :  SYNC_NOTIFY_TYPE_PATH, SYNC_NOTIFY_TYPE_NAME_NEW, etc
     * name_type_item' type include SYNC_NOTIFY_TYPE_NAME_NEW, SYNC_NOTIFY_TYPE_NAME_REMOVE,etc
     * path_type_item' type is SYNC_NOTIFY_TYPE_PATH
     * count>=1, path_type_item is compulsory, name_type_item and other_type_item are optional
     */  
		char* devstr=FileNavGetDeviceTypeStr((char*)pMsg->msg_value+3);
		if(strcmp(devstr,"UPNP")==0){
#ifndef __ROM_
			// printf("upnp device refresh broadcast message\n");
#endif	    
		}
		else if(strcmp(devstr,"FRAMECHANNEL")==0){
//			InitPreviewList();
//			Init_FileList_Prepare_List(MEDIA_PIC,SHOW_WINDOW_NUM);
#ifndef __ROM_
			// printf("framechannel device refresh broadcast message\n");
#endif	    
	    }    
		break;         	    
	case BM_NETIF_STATUS_NOTIFICATION:
		network_status=pMsg->msg_value;
		switch(network_status)
		{
			case NETIF_STATUS_READY://get IP address successful			        
			{
#ifdef BROWSER_SUPPORT
				PHWND hwnd = NULL;		
				DEV_MOUNT_INFO DevMountInfo;
				char* browser_str="BROWSER";
				char* igoogle_str="iGoogle";
				char* tempstr="";
				DevMountInfo.mount_device_type=browser_str;
				DevMountInfo.mount_device_label=igoogle_str;
				DevMountInfo.mount_point_name[0]=0;
				GetAddDevNodeItem(&DevItem, &DevMountInfo, ++DevMountNum);
				AddDevNode(DevItem, &DevList);
    
				if(AWGetTopWindow(gpFocusWin)== AWFindWinCtrlByName("WinDeviceSelect"))
				{
					hwnd = AWFindWinCtrlByName("WinDeviceSelectInfo");
					CurrentCursor = 0;
					pLeftHeadDevNode = DevList.End; //set the Lefthead device Node as the end
					RefreshDevWindow(hwnd, CurrentCursor, 0);	
				}
#endif
				network_connected_flag=1;			           
				break;	
			}				
			case NETIF_STATUS_ON: //start DHCP
				network_connected_flag=0;	
				break;
			case NETIF_STATUS_OFF: //IP is down
			{
#ifdef BROWSER_SUPPORT 
				PHWND hwnd = NULL;		
				DEV_MOUNT_INFO DevMountInfo;
				char* browser_str="BROWSER";
				DevMountInfo.mount_device_type=browser_str;
				RemoveDevNode((DEV_MOUNT_INFO*)pMsg->msg_value, &DevList, --DevMountNum);
				if(AWGetTopWindow(gpFocusWin)== AWFindWinCtrlByName("WinDeviceSelect"))
				{
					pLeftHeadDevNode = DevList.End; //set the Lefthead device Node as the end  
					CurrentCursor = 0; // set the lefthead device is the current device
					hwnd = AWFindWinCtrlByName("WinDeviceSelectInfo");			
					RefreshDevWindow(hwnd, CurrentCursor, 0);
					break;
				}
#endif
				network_connected_flag=0;	
				break;
			}                
			default:
				break;
			}
			AWGUISendNMMessage(MEDIA_SYSTEM, NM_SHOW_NETWORK_ICON, 0);        
			break;
		case BM_NETDEV_STATUS_NOTIFICATION:
		switch(pMsg->msg_value)
			{
			case NETDEV_STATUS_PLUG:
				/*usb net device plug in*/
				 usbnet_device_plug = 1;
				 break;
		       case NETDEV_STATUS_UNPLUG:
			   	/*usb net device plug out*/
				usbnet_device_plug = 0;
				if(net_entrance == TRUE){
					HWND * win = AWGetFocusWin();
					//if((strcmp(win,"WinDeviceSelect")!=0)&&(strcmp(win,"WinSetup_net_menu")!=0)){
						AWHideWindow(win);
						ReloadLogo(Logo_keyboard, sizeof(Logo_keyboard));
						GUIShowWindow("WinDeviceSelect");
						//}
					}
			   	 break;
			case NETDEV_STATUS_ON:
				/*usb net device has opened,usbnet device is enabled.*/
				break;
		       default:
			   	  break;
			}
		break;
	default:
	    break;
	}      
}
#endif /* ENABLE_NETWORK */

#ifdef  ENABLE_NETWORK_BASIC
void AWNetMsgProcess(AWMSG *pMsg)
{
	switch(pMsg->msg_type)
	{
		case MSG_INPUT_EVENT:
			break ;
		case MSG_NOTIFICATION:
#ifdef ENABLE_NETWORK
			AWNetNotificationProcess(pMsg) ;
#endif            
			break ;
		case MSG_QUIT:
			break;
		case MSG_BROADCAST:
#ifdef ENABLE_NETWORK
			AWNetBroadCastProcess(pMsg) ;
#endif
			break;
		default:
			break ;
	}    
	return ;
}

void get_ip_from_netif(void)
{
	struct netif_config net_config;

	if (netif_get_config(&net_config))
	{
					//AVOS_printf("get config error\n");
		return;
	}
	
	inet_ntoa_r(net_config.ipaddr, ip_config_info[0]);

	 if (net_config.netmask.s_addr)
			{                        	
				inet_ntoa_r(net_config.netmask, ip_config_info[1]);
			}	
			
	 if (net_config.gateway.s_addr)
			{                        	
				inet_ntoa_r(net_config.gateway, ip_config_info[2]);
			}
	 if (net_config.primary_dns.s_addr)
			{                        	
				inet_ntoa_r(net_config.primary_dns, ip_config_info[3]);
			}	
	
}

/* ENABLE_NETWORK_BASIC */
#endif
